<template>
  <back-dialog-base
    :title="title"
    :visible="visibleDialog"
    width="25rem"
    @onCommit="handleSubmit"
    @onCloesa="closeDlog"
  >
    <template #content>
      <div class="content-warp">
        <div class="left-form">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="选择预案：" prop="file">
                  <el-upload
                    :action="url"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :headers="{ Authorization: token }"
                    :before-upload="beforeUpload"
                    accept=".pdf,.docx,.doc,.xls,.xlsx,.word"
                    :on-success="successa"
                    ref="uploaddemo"
                    :value="form.file"
                    :before-remove="handleRemove"
                  >
                    <el-button planType="primary">上传文件</el-button>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="预案名称：" prop="name">
                  <el-input
                    v-model="form.name"
                    placeholder="请输入…"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预案类型：" prop="type">
                  <el-input
                    v-model="form.type"
                    placeholder="请输入…"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label-width="auto"
                  label="所属/编制单位："
                  prop="company"
                >
                  <el-input
                    v-model="form.company"
                    placeholder="请输入…"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </template>
  </back-dialog-base>
</template>

<script setup>
import { reactive, defineProps, ref, defineEmits, watch } from 'vue'
import BackDialogBase from '@/components/BackDialogBase'
import { message } from '@/utils/message'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ListId, ListSave } from '@/api/reserveData'
import store from '@/store'

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visibleDialog: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})
const uploaddemo = ref(null)
const token = store.getters.token
const headers = ref({ token: token })
const emits = defineEmits(['onReload'])
const formRef = ref(null)
const form = reactive({
  name: '',
  type: '',
  company: '',
  file: '',
  fileInfo: {
    fileName: '',
    fileSize: '',
    fileUrl: ''
  },
  planRegulateForm: {
    company: '',
    name: '',
    type: ''
  }
})
const rules = reactive({
  file: [{ required: true, message: '请上传预案文件', trigger: 'change' }],
  name: [
    {
      required: true,
      message: '预案名称不能为空',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '预案类型不能为空',
      trigger: 'blur'
    }
  ],
  company: [
    {
      required: true,
      message: '所属/编制单位不能为空',
      trigger: 'blur'
    }
  ]
})

const tagsLamp = ref([])
const tagsCamera = ref([])
const tagsScreen = ref([])
const url = ref(process.env.VUE_APP_BASE_API + '/file/upload')
const closeDlog = () => {
  uploaddemo.value.clearFiles()
  emits('onCloes')
}
const gettie = () => {
  var dataTime = new Date()
}
gettie()
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      save(Object.assign(props.rowData, form))
      console.log('验证通过')
    } else {
      console.log('验证错误')
      return false
    }
  })
}

const save = async (data) => {
  data.planRegulateForm.name = data.name
  data.planRegulateForm.type = data.type
  data.planRegulateForm.company = data.company
  const res = await ListSave(data)
  if (res) {
    message({ type: 'success', message: '预案添加成功!' })
    clearForm()
    emits('onReload')
  }
}
const getlamp = async (id) => {
  const res = await ListId({ id })
  return res
}
const handleRemove = () => {
  form.file = ''
  form.fileInfo.fileName = ''
  form.fileInfo.fileSize = ''
  form.fileInfo.fileUrl = ''
}
const beforeUpload = (file) => {
  let size = file.size / 1024 / 1024 < 50
  if (!size) {
    ElMessage({
      showClose: true,
      message: '上传文件不能大于50M！',
      type: 'warning'
    })
  }
  // // 限制文件格式类型
  // console.log('file.size', file.size)
  // const isLt10M = file.size / 1024 / 1024 < 50
  form.fileInfo.fileSize = file.size
  form.file = file.name
  // const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
  // const whiteList = ['doc', 'docx', 'pdf', 'world', 'xlsx']
  // if (whiteList.indexOf(fileSuffix) === -1) {
  //   message({ message: '上传文件只能是 jpg,png格式', type: 'warning' })
  //   return false
  // } else if (!isLt10M) {
  //   message({ type: 'error', message: '上传文件不能超过50MB哦!' })
  //   return false
  // }
  // return true
}
const uploadAction = async (options) => {
  console.log('options', options)
  // const res = await upload(options.file)
  // console.log('res', res)
}
const successa = (res) => {
  // console.log('res-success', res)
  if (res.status === 200) {
    form.fileInfo.fileName = res.data.submittedFileName
    form.fileInfo.fileSize = res.data.size
    form.fileInfo.fileUrl = res.data.url
    form.planRegulateForm.uploadingTime = gettimea(new Date())
  }
}
watch(
  () => props.rowData,
  () => {
    if (props.rowData.planId) {
      const rowDataP = getlamp(props.rowData.planId)
      //这里只回显一个，演示用，具体逻辑先不管了
      rowDataP.then((rowData) => {})
    } else {
      clearForm()
    }
  }
)

const clearForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.value = {
    fileInfo: {
      fileName: '',
      fileSize: '',
      fileUrl: ''
    },
    planRegulateForm: {
      company: '',
      name: '',
      type: ''
    }
  }
}
const gettimea = (timeStamp) => {
  //显示当前时间（年月日时分秒）
  let year = new Date(timeStamp).getFullYear()
  let month =
    new Date(timeStamp).getMonth() + 1 < 10
      ? '0' + (new Date(timeStamp).getMonth() + 1)
      : new Date(timeStamp).getMonth() + 1
  let date =
    new Date(timeStamp).getDate() < 10
      ? '0' + new Date(timeStamp).getDate()
      : new Date(timeStamp).getDate()
  let hh =
    new Date(timeStamp).getHours() < 10
      ? '0' + new Date(timeStamp).getHours()
      : new Date(timeStamp).getHours()
  let mm =
    new Date(timeStamp).getMinutes() < 10
      ? '0' + new Date(timeStamp).getMinutes()
      : new Date(timeStamp).getMinutes()
  let ss =
    new Date(timeStamp).getSeconds() < 10
      ? '0' + new Date(timeStamp).getSeconds()
      : new Date(timeStamp).getSeconds()
  let nowTime =
    year + '-' + month + '-' + date + '' + ' ' + hh + ':' + mm + ':' + ss
  return nowTime
}
</script>

<style lang="scss" scoped>
.content-warp {
  width: 100%;
  height: 100%;
  display: flex;
  .left-form {
    flex: 4;
  }
  .right-form {
    flex: 6;
    height: 780px;
    overflow: auto;
    padding-left: 60px;
    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #d6d6d680;
      border-radius: 20px;
    }
    .item-form {
      width: 100%;
      display: flex;
      margin-bottom: 30px;
      .title {
        width: 80px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        line-height: 19px;
        color: #333333;
        display: flex;
        .line-tag {
          width: 4px;
          height: 14px;
          background: #ff9502;
          border-radius: 4px;
          margin-right: 5px;
        }
      }
      .form-content {
        width: calc(100% - 120px);
        display: flex;
        flex-direction: column;
        .btns-row {
          width: 100%;
          height: 35px;
          display: flex;
          position: relative;
          margin-bottom: 6px;
          .tags {
            width: calc(100% - 45px);
            display: flex;
            column-gap: 4px;
            overflow-x: auto;
            &::-webkit-scrollbar-track-piece {
              background: #d3dce6;
            }

            &::-webkit-scrollbar {
              width: 3px;
              height: 3px;
            }

            &::-webkit-scrollbar-thumb {
              background: #ff9502;
              border-radius: 20px;
            }
          }
          .add-btn {
            width: 40px;
            height: 32px;
            background: rgba(255, 255, 255, 0.39);
            border: 1px solid #ff9502;
            border-radius: 5px;
            font-size: 12px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            line-height: 30px;
            color: #ff9502;
            text-align: center;
            position: absolute;
            right: 0;
            cursor: pointer;
            &:hover {
              background: rgba(255, 255, 255, 0.22);
            }
          }
        }
        .form-card {
          width: 100%;
          border: 1px solid #d3dbe5;
          border-radius: 4px;
          padding: 20px;
        }
      }
    }
  }
}
:deep(.el-input__inner) {
  width: 212px;
}
</style>
